﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TravelSite.Entities;
using Dapper;

namespace TravelSite.DAL.Repositories
{
    public class VacationCompanyRepository : BaseRepository<VacationCompany>
    {
        protected override string TableName
        {
            get { return "[VacationCompanies]"; }
        }

        public override IEnumerable<VacationCompany> FindAll()
        {
            string strSQL = @"  select vo.VacationCompanyId, vo.VacationCompanyName, vo.IsDefault, 
                    convert(bit, case 
                                    when 1 = 0 then 0
                                else 1 end) as CanDelete
                    from [VacationCompanies] (nolock) as vo 
                    order by vo.VacationCompanyName ";

            IEnumerable<VacationCompany> result = Connection.Query<VacationCompany>(strSQL);
            return result;
        }

        public override VacationCompany Find(int id)
        {
            VacationCompany result = Connection.Query<VacationCompany>(
                @"  select vo.VacationCompanyId, vo.VacationCompanyName, vo.IsDefault
                    from [VacationCompanies] (nolock) as vo
                    where vo.VacationCompanyId = @VacationCompanyId", new { VacationCompanyId = id }).SingleOrDefault();
            return result;
        }

        public override void Insert(VacationCompany item)
        {
            if (item.IsDefault)
                Connection.Execute(@"update VacationCompanies set IsDefault = 0");

            Connection.Execute(
                @"insert into [VacationCompanies] 
                (VacationCompanyName, IsDefault)
                values (@VacationCompanyName, @IsDefault)", item);
        }

        public override void Update(VacationCompany item)
        {
            if (item.IsDefault)
                Connection.Execute(@"update VacationCompanies set IsDefault = 0");

            Connection.Execute(
                @"update VacationCompanies
                    set VacationCompanyName = @VacationCompanyName, IsDefault = @IsDefault
                    where (VacationCompanyId = @VacationCompanyId)", item);
        }

        public override void Delete(int id)
        {
            Connection.Execute(
                @"delete 
                    from VacationCompanies
                    where (VacationCompanyId = @VacationCompanyId)", new { VacationCompanyId = id });
        }

    }
}
